package jzqb.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import haha.life.common.BelongToSqlUtils;
import haha.life.common.CutPageBean;
import haha.life.common.PermissionTypeTool;
import haha.life.common.SysTool;
import haha.life.normal.FileUtil;
import haha.life.normal.FileuploadUtils;
import haha.life.normal.TokenUtils;
import io.swagger.annotations.Api;
import jzqb.bo.PreviewBo;
import jzqb.bo.QBZSBo;
import jzqb.bo.StandardBo;
import jzqb.common.Result;
import jzqb.service.AdminPermissionService;
import jzqb.service.KnowledgeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/knowledgesss")
@Api(tags = "情报知识")
public class KnowledgeController {


    @Autowired
    KnowledgeService knowledgeService;

    @Autowired
    AdminPermissionService adminPermissionService;

    @Value("${filePath.qbzsFilePath}")
    private String qbzsFilePath;

    @Value("${filePath.qbcgFilePath}")
    private String qbcgFilePath;

    @Value("${filePath.qbzyFilePath}")
    private String qbzyFilePath;

    @Value("${filePath.ztwxFilePath}")
    private String ztwxFilePath;

    @Value("${filePath.outResourceUrl}")
    private String outResourceUrl;

    /**
     * 主页的结果集
     *
     * @param standardBo
     * @return
     */

    @PostMapping("/complexSearch")
    public Result ComplexSearch(@RequestBody StandardBo standardBo) {
        CutPageBean<StandardBo> result = knowledgeService.ComplexSearch(standardBo);
        return Result.succ(result);
    }

    /**
     * 获得 数据来源
     *
     * @param
     * @return
     */
    @PostMapping("/getDataSourceClassify")
    public Result getDataSourceClassify() {
        Result result = knowledgeService.ComplexDataSurceGroup();
        return result;
    }


    @PostMapping("/getAreaClassify")
    public Result getAreaClassify(@RequestBody StandardBo standardBo) {
        Result result = knowledgeService.ComplexSearchGroup(standardBo);
        return result;
    }

    /**
     * 获取 发表年度groupBy的数据
     *
     * @param standardBo
     * @return
     */
    @PostMapping("/getYearClassify")
    public Result getYearClassify(@RequestBody StandardBo standardBo) {
        Result result = knowledgeService.ComplexSearchGroup(standardBo);
        return result;
    }

    /**
     * 获取外部资源的详情
     */
    @PostMapping("/getOutResourceDetail")
    public Result getOutResourceDetail(@RequestBody StandardBo standardBo) {
        String string = outResourceUrl.replace("{0}", standardBo.getTableName());
        String result = string.replace("{1}", standardBo.getFileName());
        return Result.succ(result);
    }

    /**
     * 作者数据统计
     *
     * @param standardBo
     * @return
     */
    @PostMapping("/getAuthorClassify")
    public Result getAuthorClassify(@RequestBody StandardBo standardBo) {
        Result result = knowledgeService.ComplexSearchGroup(standardBo);
        return result;
    }

    /**
     * 出版单位数据统计
     *
     * @param standardBo
     * @return
     */
    @PostMapping("/getOrgClassify")
    public Result getOrgClassify(@RequestBody StandardBo standardBo) {
        Result result = knowledgeService.ComplexSearchGroup(standardBo);
        return result;
    }

    /**
     * 根据dbCode 和sysID 查询情报知识的详情
     */
    @PostMapping("/getKnowledgeDetail")
    public Result getKnowledgeDetail(@RequestBody QBZSBo qbzsBo) {
        Result result = knowledgeService.getKnowledgeDetail(qbzsBo);
        return result;
    }

    @PostMapping(value = "/preview")
    public Result preview(@RequestBody QBZSBo qbzsBo, HttpServletRequest req) {
        String userId = TokenUtils.getCurrentUserId(req);
        boolean checked = adminPermissionService.checkDataPermission(userId, qbzsBo, PermissionTypeTool.d);
        if (!checked) {
            return Result.fail("权限不足!");
        }

        StandardBo bo = knowledgeService.getLocalKnowLeage(qbzsBo);
        if (bo == null) {
            return Result.fail("文件不存在");
        }
        if (bo.getFileDistinct() == null || bo.getFileDistinct() == "") {
            return Result.fail("文件不存在");
        }
        String FilePath = "";
        if (bo.getTableName().equals(SysTool.getDBBoByKey(SysTool.QBZYUAN).getDbCode())) {
            FilePath = qbzsFilePath;
        } else if (bo.getTableName().equals(SysTool.getDBBoByKey(SysTool.YJCG).getDbCode())) {
            FilePath = qbcgFilePath;
        } else if (bo.getTableName().equals(SysTool.getDBBoByKey(SysTool.QBZY).getDbCode())) {
            FilePath = qbzyFilePath;
        }else if (bo.getTableName().equals(SysTool.getDBBoByKey(SysTool.ZTWX).getDbCode())) {
            FilePath = ztwxFilePath;
        }
        FilePath = FileUtil.calculateAbstractPath(bo.getFileDistinct(), FilePath);
        byte[] imageBinary = FileuploadUtils.getImageBinary(FilePath);
        if (imageBinary == null) {
            return Result.fail("文件不存在");
        }
        // 这里对下载频次进行修改
        StandardBo standardBo = knowledgeService.getBoById(qbzsBo);
        String downTime = standardBo.getDownloadTimes();
        if ("".equals(downTime) || downTime == null) {
            downTime = "0";
        }
        Integer times = Integer.parseInt(downTime);
        times = times + 1;
        standardBo.setDownloadTimes(times.toString());
        Boolean result = knowledgeService.updateDownTime(standardBo);
        PreviewBo previewBo = new PreviewBo();
        previewBo.setPdf(imageBinary);
        previewBo.setTitle(bo.getFileDistinct());

        //插入下载日志
        adminPermissionService.addBrowseDownLoadLog("d", userId, bo);

        return Result.succ(previewBo);
    }

    @PostMapping(value = "/onlineVisit")
    public Result onlineVisit(@RequestBody QBZSBo qbzsBo, HttpServletRequest req) {
        String userId = TokenUtils.getCurrentUserId(req);
        boolean checked = adminPermissionService.checkDataPermission(userId, qbzsBo, PermissionTypeTool.p);
        if (!checked) {
            return Result.fail("权限不足!");
        }

        StandardBo bo = knowledgeService.getLocalKnowLeage(qbzsBo);
        if (bo == null) {
            return Result.fail("文件不存在");
        }
        if (bo.getFileDistinct() == null || bo.getFileDistinct() == "") {
            return Result.fail("文件不存在");
        }
        if (!bo.getFileDistinct().contains(".pdf")) {
            return Result.fail("不支持的文件类型，请下载后观看");
        }
        String FilePath = "";
        if (bo.getTableName().equals(SysTool.getDBBoByKey(SysTool.QBZYUAN).getDbCode())) {
            FilePath = qbzsFilePath;
        } else if (bo.getTableName().equals(SysTool.getDBBoByKey(SysTool.YJCG).getDbCode())) {
            FilePath = qbcgFilePath;
        } else if (bo.getTableName().equals(SysTool.getDBBoByKey(SysTool.QBZY).getDbCode())) {
            FilePath = qbzyFilePath;
        }else if (bo.getTableName().equals(SysTool.getDBBoByKey(SysTool.ZTWX).getDbCode())) {
            FilePath = ztwxFilePath;
        }
        FilePath = FileUtil.calculateAbstractPath(bo.getFileDistinct(), FilePath);
        byte[] imageBinary = FileuploadUtils.getImageBinary(FilePath);
        if (imageBinary == null) {
            return Result.fail("文件不存在");
        }
        PreviewBo previewBo = new PreviewBo();
        previewBo.setPdf(imageBinary);
        previewBo.setTitle(bo.getFileDistinct());
        //插入浏览日志
        adminPermissionService.addBrowseDownLoadLog("p", userId, bo);

        return Result.succ(previewBo);
    }

    /**
     * 根据点击条件 和数据库查询知识图谱相关文章
     */
    @GetMapping("/ralatedArticlesList")
    public Result ralatedArticlesList(@RequestParam("dbCodeList") String dbCodeList, @RequestParam("keyWord") String keyWord) {
        if (!"".equals(keyWord) && keyWord != null) {
            String sql = dbCodeList + " WHERE " + keyWord + " ORDER BY 发表时间 DESC LIMIT 7";
            List<StandardBo> list = knowledgeService.ralatedArticlesList(sql);
            return Result.succ(list);
        }
        return Result.succ("");
    }

    @PostMapping("/getResultByAuthor")
    public Result getResultByAuthor(@RequestBody StandardBo standardBo) {
        if (standardBo.getAuthor() == "" || standardBo.getAuthor() == null) {
            return Result.succ("");
        }
        String dbString =  SysTool.getTableNameByDBJSON();
        standardBo.setDateSourceString(dbString);
        String[] strArr = standardBo.getAuthor().split(";");
        if (strArr != null && strArr.length > 0) {
            String BelongToSql = BelongToSqlUtils.getBelongToSql(strArr, "作者");
            standardBo.setAuthorBelongToSql(BelongToSql);
            List<StandardBo> standardBos = knowledgeService.getResultByAuthor(standardBo);
            return Result.succ(standardBos);
        }
        return Result.succ("");
    }

    @PostMapping("/getResultByOrganization")
    public Result getResultByOrganization(@RequestBody StandardBo standardBo) {
            if (standardBo.getLiteratureSources() == "" || standardBo.getLiteratureSources() == null) {
                return Result.succ("");
            }
            // 从配置文件中读取，并且获取所有的表名 用 ，连接
             String dbString =  SysTool.getTableNameByDBJSON();
             standardBo.setDateSourceString(dbString);
            String[] strArr = standardBo.getLiteratureSources().split(";");
            if (strArr != null && strArr.length > 0) {
                String BelongToSql = BelongToSqlUtils.getBelongToSql(strArr, "机构");
                standardBo.setOrganizationBelongToSql(BelongToSql);
                List<StandardBo> standardBos = knowledgeService.getResultByOrganization(standardBo);
                return Result.succ(standardBos);
            }
            return Result.succ("");
    }

    @PostMapping("/getResultByKeyword")
    public Result getResultByKeyword(@RequestBody StandardBo standardBo) {
        if (standardBo.getKeyStr() == "" || standardBo.getKeyStr() == null) {
            return Result.succ("");
        }
        String dbString =  SysTool.getTableNameByDBJSON();
        standardBo.setDateSourceString(dbString);
        String[] strArr = standardBo.getKeyStr().split(";");
        if (strArr != null && strArr.length > 0) {
            String BelongToSql = BelongToSqlUtils.getBelongToSql(strArr, "关键词");
            standardBo.setKeywordBelongToSql(BelongToSql);
            List<StandardBo> standardBos = knowledgeService.getResultByKeyword(standardBo);
            return Result.succ(standardBos);
        }
        return Result.succ("");
    }

    //列表获取相似文献
    @PostMapping("/getRalatedArticlesList")
    public Result getRalatedArticlesList(@RequestBody StandardBo standardBo) {
        String dbCode= "";
        String dataBases =  FileUtil.readJsonFile("db.json");
        List<JSONObject> dataBasesList = JSON.parseArray(dataBases, JSONObject.class);
        for (JSONObject dataBaseobj:dataBasesList){
            if (dataBaseobj.get("isOpen").equals(true)) {
                dbCode += dataBaseobj.get("dbCode")+ ",";
            }
        }
        if(!"".equals(dbCode)){
            dbCode = dbCode.substring(0,dbCode.length()-1);
        }
        standardBo.setDbCodeStr(dbCode);
        List<StandardBo> list = knowledgeService.getRalatedArticlesList(standardBo);
        return Result.succ(list);
    }
}
